<script setup lang="ts">
import { computed, ref } from 'vue'
import { message } from '@/utils/message'
import { ModalShowTitle, ModalShowType } from '@/types/common'
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessageBox,
  ElOption,
  ElSelect,
  FormInstance,
} from 'element-plus'
import { addMcp, editMcp, getMcpDetail } from '@/api/mcp-mall/mcp-mall'
import useDictStore from '@/store/modules/dict'

const props = defineProps<{
  modalShow: ModalShowType
  mcpId: string | null
  onSearch?: () => Promise<void>
}>()

const emit = defineEmits<{
  (e: 'update:modalShow', type: ModalShowType): void
}>()

const modalShow = computed({
  get() {
    return props.modalShow
  },
  set(value) {
    emit('update:modalShow', value)
  },
})

const ruleFormRef = ref<FormInstance>()
const formData = ref({
  mcpName: '',
  alias: '',
  type: '',
  provider: '',
  mcpImgUrl: '',
  tags: '',
  description: '',
  config: '',
  status: '0', // 默认状态
})

const { mcp_types } = useDictStore().getDicts('mcp_types') // 使用字典
const loading = ref(false)

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const ok = await formEl.validate()
  if (!ok) return

  loading.value = true
  try {
    if (modalShow.value === ModalShowType.New) {
      await addMcp(formData.value)
    } else {
      await editMcp({ ...formData.value, mcpId: props.mcpId })
    }
    message('操作成功', { type: 'success' })
    modalShow.value = ModalShowType.Hide
    await props.onSearch?.()
  } catch (error) {
    message('操作失败', { type: 'error' })
  } finally {
    loading.value = false
  }
}

const rules = {
  mcpName: [{ required: true, message: '请输入MCP名称', trigger: 'blur' }],
  alias: [{ required: true, message: '请输入MCP别名', trigger: 'blur' }],
  mcpImgUrl: [{ required: true, message: '请输入MCP Logo url', trigger: 'blur' }],
  tags: [{ required: true, message: '请输入标签', trigger: 'blur' }],
  config: [{ required: true, message: '请输入MCP配置', trigger: 'blur' }],
  type: [{ required: true, message: '请选择MCP类型', trigger: 'change' }],
}

const resetFields = () => {
  ruleFormRef.value?.resetFields()
  formData.value = {
    mcpName: '',
    alias: '',
    type: '',
    provider: '',
    mcpImgUrl: '',
    tags: '',
    description: '',
    config: '',
    status: '',
  }
}

const onOpen = async () => {
  if (props.mcpId) {
    const { data } = await getMcpDetail(props.mcpId)
    formData.value = { ...data }
  }
}

const beforeCloseDialog = () => {
  if (modalShow.value === ModalShowType.New) {
    ElMessageBox.confirm('即将关闭此弹窗，您填写的内容将丢失。是否继续？', '确认关闭', {
      confirmButtonText: '继续关闭',
      cancelButtonText: '取消',
    })
      .then(() => {
        resetFields()
        modalShow.value = ModalShowType.Hide
      })
      .catch(() => {})
  } else {
    resetFields()
    modalShow.value = ModalShowType.Hide
  }
}
</script>

<template>
  <el-drawer
    :model-value="modalShow !== ModalShowType.Hide"
    :title="ModalShowTitle.get(modalShow) + 'MCP'"
    :before-close="beforeCloseDialog"
    size="50%"
    @open="onOpen"
    @closed="resetFields"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="130px"
    >
      <el-form-item label="MCP名称" prop="mcpName">
        <el-input v-model="formData.mcpName" placeholder="请输入MCP名称" />
      </el-form-item>
      <el-form-item label="MCP别名" prop="alias">
        <el-input v-model="formData.alias" placeholder="请输入MCP别名" />
      </el-form-item>
      <el-form-item label="MCP类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择MCP类型">
          <el-option
            v-for="item in mcp_types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提供方" prop="provider">
        <el-input v-model="formData.provider" placeholder="请输入MCP提供方" />
      </el-form-item>
      <el-form-item label="MCP LOGO图标" prop="mcpImgUrl">
        <el-input v-model="formData.mcpImgUrl" placeholder="请输入LOGO图标" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input v-model="formData.tags" placeholder="请输入标签" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="配置" prop="config">
        <el-input v-model="formData.config" type="textarea" placeholder="请输入MCP配置" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="beforeCloseDialog">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm(ruleFormRef)">
        {{ modalShow === ModalShowType.New ? '创建MCP' : '确认' }}
      </el-button>
    </template>
  </el-drawer>
</template>
